#include"head.h"
#include"input.h"

int input(struct Node* Hnode, char c, int y, int x)
{
    struct Node* currentc = Hnode;
    struct Node* currentr;
    struct Node* newnode, * previous, * next, * temp;
    int i, j;
    for (i = 1; i < y; i++)
    {
        if (currentc->next != NULL)
        {
            currentc = currentc->next;
        }
        else
        {
            break;
        }
    }
    if (i == y)
    {
        currentr = currentc->data.cnode;
        for (j = 1; j < x; j++)
        {
            if (currentr->next != NULL)
            {
                currentr = currentr->next;
            }
            else
            {
                break;
            }
        }
        if (j < x)
        {
            if (c == '\r')
            {
                currentr = AddNode(currentr);
                currentr->data.rnode[0] = 0;
                currentr->data.rnode[1] = '\n';
                return 3;
            }
            if (j >= ROWCHAR)
            {
                currentc = AddNode(currentc);
                currentc->data.cnode = malloc(sizeof(struct Node));
                currentr = currentc->data.cnode;
                currentr->previous = currentr->next = NULL;
                currentr->data.rnode[0] = 0;
                currentr->data.rnode[1] = c;
                return 1;
            }
            currentr = AddNode(currentr);
            currentr->data.rnode[0] = 0;
            currentr->data.rnode[1] = c;
            return 1;
        }
    }
    if (currentc->data.cnode == NULL)
    {
        currentc->data.cnode = malloc(sizeof(struct Node));
        currentc->data.cnode->previous = currentc->data.cnode->next = NULL;
        currentc->data.cnode->data.rnode[0] = 0x00;
        currentc->data.cnode->data.rnode[1] = c;
        return 1;
    }
    previous = currentc->previous;
    next = currentc->next;
    currentr = currentc->data.cnode;
    if (x == 1)
    {
        newnode = InsertNode(currentr);
        newnode->data.rnode[0] = 0x00;
        newnode->data.rnode[1] = c;
        currentc->data.cnode = newnode;
    }
    else
    {
        for (i = 1; i < x; i++)
        {
            if (currentr->next != NULL)
            {
                currentr = currentr->next;
            }
            else
            {
                break;
            }
        }
        newnode = InsertNode(currentr);
        newnode->data.rnode[0] = 0x00;
        newnode->data.rnode[1] = c;
    }
    if (c == '\r')
    {
        newnode->data.rnode[1] = '\n';
        newnode->next = NULL;
        currentr->previous = NULL;
        currentc = AddNode(currentc);
        currentc->data.cnode = currentr;
        return 1;
    }
    SortNode(currentc);
    return 1;
}